package com.example.petchating.camera


import com.badlogic.gdx.Gdx
import com.badlogic.gdx.graphics.OrthographicCamera
import com.badlogic.gdx.utils.viewport.FitViewport
import com.example.petchating.entities.Pet
import com.example.petchating.map.MapLoader

class CameraController(
    private val mapLoader: MapLoader,
    private val cameraWidth: Float = 150f
) {
    //视口中心位置
    private var targetX : Float = 0.0f
    private var targetY : Float = 0.0f
    //缓存相机状态
    var lastCameraX = 0f
    var lastCameraY = 0f
    //视口高度
    private val cameraHeight: Float = cameraWidth*Gdx.graphics.height/ Gdx.graphics.width
    val camera: OrthographicCamera = OrthographicCamera()
    //viewport：游戏世界视口
    val viewport: FitViewport

    private val cameraSpeed = 5f // 相机移动速度

    init {
        // 初始化摄像机并设置大小
        // etToOrtho 方法用于设置相机为正交投影模式
        camera.setToOrtho(false, cameraWidth, cameraHeight)
        viewport = FitViewport(cameraWidth, cameraHeight, camera)
    }
    // 设置视口为适配摄影机尺寸
    fun applyViewport() {
        viewport.apply()
    }

    fun updateCamera(pet : Pet,delta: Float) {
        //跟新相机坐标至宠物坐标
        setCameraPosition(pet)
        //相机边界
        val minX = cameraWidth / 2f
        val maxX = mapLoader.mapWidth - cameraWidth / 2f
        val minY = cameraHeight / 2f
        val maxY = mapLoader.mapHeight - cameraHeight / 2f
        //相机可移动范围
        val clampedX = targetX.coerceIn(minX, maxX)
        val clampedY = targetY.coerceIn(minY, maxY)
        //当前/更新前相机的位置
        val currentX = camera.position.x
        val currentY = camera.position.y

        // 插值计算新的相机位置
        val newX = currentX + (clampedX - currentX) * cameraSpeed * delta
        val newY = currentY + (clampedY - currentY) * cameraSpeed * delta

        camera.position.set(newX, newY, 0f)
        camera.update()
    }

    fun setCameraPosition(pet : Pet){
        targetX = pet.getX()
        targetY = pet.getY()
    }
}
